import { IconGroupEntry } from "./IconGroupEntry.ts";
import { IconGroup } from "./IconGroup.ts";
import { IconType } from "./constants/IconType.ts";

export class IconEntry {
  width?: number
  height?: number
  type?: number
  iconGroup: IconGroup
  iconGroupEntry: IconGroupEntry
  dataReader: IPEFileReader
  offset: number
  dataSize: number
  static PNG_MAGIC = '89504e470d0a1a0a' as const
  static ICO_MAGIC = '28000000' as const

  constructor(
    dataReader: IPEFileReader,
    iconGroup: IconGroup,
    iconGroupEntry: IconGroupEntry,
    dataSize: number
  ) {
    this.dataReader = dataReader
    this.offset = dataReader.getOffset()
    this.iconGroup = iconGroup
    this.iconGroupEntry = iconGroupEntry
    this.dataSize = dataSize
  }

  async read() {
    this.dataReader.setOffset(this.offset)
    this.width = this.iconGroupEntry.width
    this.height = this.iconGroupEntry.height
    const buffer: ArrayBuffer = await this.dataReader.readBuffer(8)
    const dataView: DataView = new DataView(buffer)
    let str = ''
    for (let i = 0; i < 8; i++) {
      const char = dataView.getUint8(i)
      const hexChar = char.toString(16).padStart(2, '0')
      str += hexChar
      if (i == 3 && str == IconEntry.ICO_MAGIC) {
        this.type = IconType.ICO
      }
    }
    if (str == IconEntry.PNG_MAGIC) {
      this.type = IconType.PNG
      this.dataReader.setOffset(this.offset + 16)
      const buffer = await this.dataReader.readBuffer(8)
      const dataView = new DataView(buffer)
      this.width = dataView.getUint32(0)
      this.height = dataView.getUint32(4)
      this.iconGroupEntry.width = this.width
      this.iconGroupEntry.height = this.height
    }
  }

  async getData() {
    this.dataReader.setOffset(this.offset)
    const buffer = await this.dataReader.readBuffer(this.dataSize)
    const unit8 = new Uint8Array(buffer)
    return new Uint8Array([
      ...this.iconGroup.getData(),
      ...this.iconGroupEntry.getData(),
      ...unit8
    ])

  }


}
